package com.example.heipictureserver.mangger.websocket.disruptor; 
 
 /*
  *@Description 类功能简要描述
  *@Author bwg
  *@Date 2025/2/13 21:13
*/

import com.example.heipictureserver.mangger.websocket.modal.PictureEditRequestMessage;
import com.example.heipictureserver.modal.domain.User;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;

/**
 * 图片编辑事件生产者
 */
@Component
@Slf4j
public class PictureEditEventProducer {

 @Resource
 private Disruptor<PictureEditEvent> pictureEditEventDisruptor;

 /**
  * 发布事件
  *
  * @param pictureEditRequestMessage
  * @param session
  * @param user
  * @param pictureId
  */
 public void publishEvent(PictureEditRequestMessage pictureEditRequestMessage, WebSocketSession session, User user, String pictureId) {
  RingBuffer<PictureEditEvent> ringBuffer = pictureEditEventDisruptor.getRingBuffer();
  // 获取到可以防止事件的位置
  long next = ringBuffer.next();
  PictureEditEvent pictureEditEvent = ringBuffer.get(next);
  pictureEditEvent.setPictureEditRequestMessage(pictureEditRequestMessage);
  pictureEditEvent.setSession(session);
  pictureEditEvent.setUser(user);
  pictureEditEvent.setPictureId(pictureId);
  // 发布事件
  ringBuffer.publish(next);
 }

 /**
  * 优雅停机
  */
 @PreDestroy
 public void destroy() {
  pictureEditEventDisruptor.shutdown();
 }
}
